﻿using System.Collections.ObjectModel;
using System.Data.Linq;
using System.Linq;

namespace PersonaLibrary.Data
{
    public partial class Organization
    {
        private EventsEntitySet<Department> lazyDepartments;
        private EntityRef<Organization> _parent = default(EntityRef<Organization>);
        private bool _canLazyDepartmentsLoad;

        public EventsEntitySet<Department> LazyDepartments
        {
            get
            {
                if (lazyDepartments == null && _canLazyDepartmentsLoad)
                {
                    lazyDepartments = new EventsEntitySet<Department>(Departments.OrderBy(x => x.Name))
                                          {
                                              EntityAddedFilter = x => x.OrganizationId == Id
                                          };
                }
                return lazyDepartments;
            }
        }

        //[System.Data.Linq.Mapping.AssociationAttribute(Name = "Organization_Organization", Storage = "Parent", ThisKey = "ParentOrganization", OtherKey = "Id", IsForeignKey = true)]
        public Organization Parent
        {
            get
            {
                return _parent.Entity;
            }
            set
            {
				SendPropertyChanging();
				_parent.Entity = value;

                if ((value != null))
                    ParentOrganization = value.Id;
                else
                    ParentOrganization = default(int?);

				SendPropertyChanged("Parent");
            }
        }

        public void LoadDepartment()
        {
            _canLazyDepartmentsLoad = true;
            SendPropertyChanged("LazyDepartments");
        }

        public override string ToString()
        {
			if (!string.IsNullOrEmpty(Ownership))
				return string.Concat(Ownership, " ", '"', Name, '"');

        	return Name;
        }

        public override void Detach()
        {
            _parent = default(EntityRef<Organization>);
            Departments = default(EntitySet<Department>);
            base.Detach();
        }

        partial void OnCreated()
        {
        }
        
    }
}
